﻿
using System;
using Family.Data.Mappings;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace Family.Data.Factories
{
    public class TestFactory : NHFactory
    {
        private static Configuration config;

        public TestFactory(String configKey) : base(configKey) { }

        public override FluentConfiguration GetConfiguration(String configKey)
        {
            var db = SQLiteConfiguration.Standard.InMemory().ConnectionString(cs => cs.FromConnectionStringWithKey(configKey))
                .Dialect("NHibernate.Dialect.SQLiteDialect")
                .Driver("NHibernate.Driver.SQLite20Driver")
                .Provider("NHibernate.Connection.DriverConnectionProvider")
                .ProxyFactoryFactory("NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle")
                .ShowSql();

            return Fluently.Configure()
                .Database(db)
                //.Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf<Product>()
                //.Where(x => x.Namespace.EndsWith("Model"))));
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<ProductMap>());
        }

        protected override ISessionFactory CreateSessionfactory()
        {
            return GetConfiguration(configKey)
                .ExposeConfiguration(cfg => config = cfg)
                .BuildSessionFactory();
        }

        public override ISession OpenSession()
        {
            ISession session = SessionFactory.OpenSession();
            new SchemaExport(config).Execute(true, true, false, session.Connection, null);
            return session;
        }
    }
}
